<template>
  <div class="member-list-view">
    <el-card>
      <!-- 工具栏 -->
      <div class="toolbar">
        <el-button type="success" @click="showCreateMemberDialog = true">
          <el-icon><Plus /></el-icon>
          创建会员
        </el-button>
        <el-button type="primary" :disabled="!multipleSelection.length || multipleSelection.some(m => m.status === '已注销')" @click="showBatchTag = true">批量标签</el-button>
        <el-button type="primary" :disabled="!multipleSelection.length || multipleSelection.some(m => m.status === '已注销')" @click="showBatchPoint = true">批量积分</el-button>
        <!-- <el-button type="primary" :disabled="!multipleSelection.length || multipleSelection.some(m => m.status === '已注销')" @click="openBatchCustomerServiceDialog">批量分配客服</el-button> -->
        <el-button type="warning" @click="viewApprovalStatus">查看审批状态</el-button>
        <el-button type="info" @click="showColumnDialog = true">显示列</el-button>
      </div>
      <!-- 搜索栏 -->
      <el-form :inline="false" :model="searchForm" class="search-panel" label-width="80px" size="small">
        <!-- 第一行：基本信息 -->
        <el-row :gutter="16">
                      <el-col :span="6">
              <el-form-item label="会员ID">
                <el-input v-model="searchForm.id" placeholder="请输入会员ID" clearable style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="会员昵称">
                <el-input v-model="searchForm.nickname" placeholder="请输入会员昵称" clearable style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="手机号">
                <el-input v-model="searchForm.phone" placeholder="请输入国际手机号" clearable style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="用户状态">
                <el-select v-model="searchForm.status" placeholder="全部" clearable style="width: 100%;">
                  <el-option label="在用" value="在用" />
                  <el-option label="已注销" value="已注销" />
                </el-select>
              </el-form-item>
            </el-col>
        </el-row>
        
        <!-- 第二行：扩展信息 -->
        <el-row :gutter="16">
          <el-col :span="6">
            <el-form-item label="APP下载">
              <el-select v-model="searchForm.appDownload" placeholder="全部" clearable style="width: 100%;">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="会员类型">
              <el-select v-model="searchForm.memberType" placeholder="全部" clearable style="width: 100%;">
                <el-option label="B类" value="B" />
                <el-option label="C类" value="C" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结算方式">
              <el-select v-model="searchForm.settlementType" placeholder="全部" clearable style="width: 100%;">
                <el-option label="JPY" value="JPY" />
                <el-option label="CNY" value="CNY" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所属客服">
              <el-select v-model="searchForm.customerService" placeholder="全部" clearable style="width: 100%;">
                <el-option label="待分配" value="待分配" />
                <el-option v-for="service in customerServiceList" :key="service" :label="service" :value="service" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 第三行：用户属性 -->
        <el-row :gutter="16">
          <el-col :span="6">
            <el-form-item label="用户标签">
              <el-select v-model="searchForm.tags" multiple placeholder="全部" clearable style="width: 100%;">
                <el-option v-for="tag in allTags" :key="tag" :label="tag" :value="tag" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="用户等级">
              <el-select v-model="searchForm.levels" multiple placeholder="全部" clearable style="width: 100%;">
                <el-option v-for="level in allLevels" :key="level" :label="level" :value="level" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="超级客服">
              <el-select v-model="searchForm.superService" placeholder="全部" clearable style="width: 100%;">
                <el-option label="开启" :value="true" />
                <el-option label="关闭" :value="false" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="黑名单">
              <el-select v-model="searchForm.isBlacklisted" placeholder="全部" clearable style="width: 100%;">
                <el-option label="是" :value="true" />
                <el-option label="否" :value="false" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 第四行：范围搜索 -->
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="账户余额">
              <div class="range-inputs">
                <el-input v-model.number="searchForm.balanceMin" placeholder="最小" />
                <span class="range-sep">-</span>
                <el-input v-model.number="searchForm.balanceMax" placeholder="最大" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="注册时间">
              <el-date-picker v-model="searchForm.registerTime" type="datetimerange" range-separator="至" start-placeholder="开始" end-placeholder="结束" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="地区">
              <el-cascader v-model="searchForm.region" :options="regionOptions" clearable style="width: 100%;" placeholder="请选择国家/省/市/区" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 第五行：备注搜索 -->
        <el-row :gutter="16">
          <el-col :span="6">
            <el-form-item label="备注">
              <el-input v-model="searchForm.remark" placeholder="请输入备注关键词" clearable style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="18"></el-col>
        </el-row>
        
        <!-- 操作按钮 -->
        <el-row>
          <el-col :span="24" class="search-actions">
            <el-button type="primary" @click="onSearch">查询</el-button>
            <el-button @click="onReset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
      <!-- 表格 -->
      <el-table
        :data="pagedData"
        border
        stripe
        style="width: 100%; margin-top: 16px;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" :selectable="(row: any) => row.status !== '已注销'" />
        <el-table-column
          v-for="col in visibleColumns"
          :key="col.prop"
          :prop="col.prop"
          :label="col.label"
          :width="col.width"
        >
          <template v-if="col.prop === 'nickname'" #default="scope">
            <el-link type="primary" @click="scope.row.status !== '已注销' && onShowDetail(scope.row)" :disabled="scope.row.status === '已注销'">{{ scope.row.nickname }}</el-link>
          </template>
          <template v-else-if="col.prop === 'appDownload'" #default="scope">
            <el-tag :type="scope.row.appDownload === '是' ? 'success' : 'info'">{{ scope.row.appDownload }}</el-tag>
          </template>
          <template v-else-if="col.prop === 'wechatBind'" #default="scope">
            <el-tag :type="scope.row.wechatBind === '是' ? 'success' : 'info'">{{ scope.row.wechatBind }}</el-tag>
          </template>
          <template v-else-if="col.prop === 'tags'" #default="scope">
            <el-tag v-for="tag in scope.row.tags" :key="tag" type="info" style="margin-right: 4px;">{{ tag }}</el-tag>
          </template>
          <template v-else-if="col.prop === 'status'" #default="scope">
            <el-tag :type="scope.row.status === '在用' ? 'success' : 'danger'">{{ scope.row.status }}</el-tag>
          </template>
          <template v-else-if="col.prop === 'isBlacklisted'" #default="scope">
            <el-tag :type="scope.row.isBlacklisted ? 'danger' : 'success'">{{ scope.row.isBlacklisted ? '是' : '否' }}</el-tag>
          </template>
          <template v-else-if="col.prop === 'memberType'" #default="scope">
            <el-tag :type="scope.row.memberType === 'B' ? 'primary' : 'success'">{{ scope.row.memberType }}</el-tag>
          </template>
          <template v-else-if="col.prop === 'settlementType'" #default="scope">
            <el-tag :type="scope.row.settlementType === 'JPY' ? 'warning' : 'info'">{{ scope.row.settlementType }}</el-tag>
          </template>
          <template v-else-if="col.prop === 'customerService'" #default="scope">
            <el-tag :type="scope.row.customerService === '待分配' ? 'warning' : 'info'" size="small">
              {{ scope.row.customerService }}
            </el-tag>
          </template>
          <template v-else-if="col.prop === 'superService'" #default="scope">
            <el-tag :type="scope.row.superService ? 'success' : 'info'" size="small">
              {{ scope.row.superService ? '开启' : '关闭' }}
            </el-tag>
          </template>

          <template v-else-if="col.prop === 'remark'" #default="scope">
            <div v-if="scope.row.isEditingRemark" class="remark-edit">
              <el-input 
                v-model="scope.row.tempRemark" 
                size="small"
                @blur="saveRemarkInline(scope.row)"
                @keyup.enter="saveRemarkInline(scope.row)"
                @keyup.esc="cancelEditRemark(scope.row)"
                ref="remarkInput"
                autofocus
              />
            </div>
            <div v-else class="remark-display" @click="startEditRemark(scope.row)">
              <span v-if="scope.row.remark" class="remark-text" :title="scope.row.remark">
                {{ scope.row.remark }}
              </span>
              <span v-else style="color: #c0c4cc;">点击添加备注</span>
              <el-icon class="edit-icon"><EditPen /></el-icon>
            </div>
          </template>
          <template v-else-if="col.prop === 'phone'" #default="scope">
            {{ maskAnyPhone(scope.row.phone) }}
          </template>
          <template v-else-if="col.prop === 'balance'" #default="scope">
            <span v-if="scope.row.memberType === 'B'">
              <el-tag type="warning" size="small" style="margin-right: 4px;">JPY</el-tag>
              {{ scope.row[col.prop] }}
            </span>
            <span v-else style="color: #c0c4cc;">--</span>
          </template>
          <template v-else-if="col.prop === 'exchangeRate'" #default="scope">
            <span v-if="scope.row.memberType === 'B' || scope.row.memberType === 'C'">
              {{ getMemberExchangeRate(scope.row) }}
              <!-- 调试信息 -->
              <span v-if="scope.row.exchangeRate" style="font-size: 10px; color: #999;">(自定义)</span>
              <span v-else style="font-size: 10px; color: #999;">(基础)</span>
            </span>
            <span v-else style="color: #c0c4cc;">--</span>
          </template>
          <template v-else-if="col.prop === 'serviceFee'" #default="scope">
            <span v-if="scope.row.memberType === 'B' || scope.row.memberType === 'C'">
              <!-- 如果会员有自定义手续费，显示自定义值 -->
              <span v-if="scope.row.serviceFee">
                <el-tag type="success" size="small" style="margin-right: 4px;">自定义</el-tag>
                {{ scope.row.serviceFee }}円
              </span>
              <!-- 否则显示基础设置的分站点手续费标签 -->
              <span v-else>
                <el-tag type="info" size="small" style="margin-right: 4px;">基础设置</el-tag>
                <div style="margin-top: 4px;">
                  <el-tag v-for="feeTag in getDefaultServiceFeeTags(scope.row.memberType)" :key="feeTag.id" size="small" style="margin-right: 2px; margin-bottom: 2px; font-size: 10px;">
                    {{ feeTag.site }}:{{ feeTag.fee }}円
                  </el-tag>
                </div>
              </span>
            </span>
            <span v-else style="color: #c0c4cc;">--</span>
          </template>
          <template v-else-if="col.prop === 'serviceRate'" #default="scope">
            <span v-if="scope.row.memberType === 'B'">
              <!-- 如果会员有自定义服务费率，显示自定义值 -->
              <span v-if="scope.row.serviceRate">
                <el-tag type="success" size="small" style="margin-right: 4px;">自定义</el-tag>
                {{ scope.row.serviceRate }}%
              </span>
              <!-- 否则显示基础设置的分站点服务费率 -->
              <span v-else>
                <el-tag type="info" size="small" style="margin-right: 4px;">基础设置</el-tag>
                <div style="margin-top: 4px;">
                  <el-tag v-for="site in getDefaultServiceRateSites(scope.row.memberType)" :key="site.site" size="small" style="margin-right: 2px; margin-bottom: 2px;">
                    {{ site.site }}: {{ site.rate }}%
                  </el-tag>
                </div>
              </span>
            </span>
            <span v-else style="color: #c0c4cc;">--</span>
          </template>
          <template v-else-if="col.prop === 'depositRatio'" #default="scope">
            <span v-if="scope.row.memberType === 'B'">
              <!-- 如果会员有自定义保证金比例，显示自定义值 -->
              <span v-if="scope.row.depositRatio">
                <el-tag type="success" size="small" style="margin-right: 4px;">自定义</el-tag>
                {{ scope.row.depositRatio }}%
              </span>
              <!-- 否则显示基础设置的分站点保证金比例 -->
              <span v-else>
                <el-tag type="info" size="small" style="margin-right: 4px;">基础设置</el-tag>
                <div style="margin-top: 4px;">
                  <el-tag v-for="site in getDefaultDepositRatioSites(scope.row.memberType)" :key="site.site" size="small" style="margin-right: 2px; margin-bottom: 2px;">
                    {{ site.site }}: {{ site.ratio }}%
                  </el-tag>
                </div>
              </span>
            </span>
            <span v-else style="color: #c0c4cc;">--</span>
          </template>
          <template v-else #default="scope">
            {{ scope.row[col.prop] }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="320" fixed="right">
          <template #default="scope">
            <div v-if="scope.row.memberType === 'B'">
              <el-button
                size="small"
                type="primary"
                @click="viewPaymentDetail(scope.row)"
                :disabled="scope.row.status === '已注销'"
              >
                支付明细
              </el-button>
              <el-button
                size="small"
                type="success"
                @click="openRechargeDialog(scope.row)"
                :disabled="scope.row.status === '已注销'"
                style="margin-left: 4px;"
              >
                充值
              </el-button>
              <el-button
                size="small"
                type="warning"
                @click="openRefundDialog(scope.row)"
                :disabled="scope.row.status === '已注销'"
                style="margin-left: 4px;"
              >
                退款
              </el-button>
              <el-button
                size="small"
                type="info"
                @click="openAutoBidDialog(scope.row)"
                :disabled="scope.row.status === '已注销'"
                style="margin-left: 4px;"
              >
                自动出价配置
              </el-button>
            </div>
            <div v-else-if="scope.row.memberType === 'C'">
              <el-button
                size="small"
                type="warning"
                @click="openConvertToBDialog(scope.row)"
                :disabled="scope.row.status === '已注销'"
              >
                转为B类
              </el-button>
              <el-button
                size="small"
                type="info"
                @click="openAutoBidDialog(scope.row)"
                :disabled="scope.row.status === '已注销'"
                style="margin-left: 4px;"
              >
                自动出价配置
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 16px; text-align: right;">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="filteredData.length"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>
    <!-- 批量标签弹窗 -->
    <el-dialog v-model="showBatchTag" title="批量标签" width="400px">
      <el-form :model="batchTagForm">
        <el-form-item label="操作类型">
          <el-radio-group v-model="batchTagForm.type">
            <el-radio label="add">增加标签</el-radio>
            <el-radio label="remove">减少标签</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="标签内容">
          <el-select v-model="batchTagForm.tags" multiple placeholder="请选择标签">
            <el-option v-for="tag in allTags" :key="tag" :label="tag" :value="tag" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showBatchTag = false">取消</el-button>
        <el-button type="primary" @click="onBatchTagConfirm">确认</el-button>
      </template>
    </el-dialog>
    <!-- 批量积分弹窗 -->
    <el-dialog v-model="showBatchPoint" title="批量积分" width="400px">
      <el-form :model="batchPointForm">
        <el-form-item label="操作类型">
          <el-radio-group v-model="batchPointForm.type">
            <el-radio label="add">增加积分</el-radio>
            <el-radio label="remove">减少积分</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="积分数">
          <el-input-number v-model="batchPointForm.points" :min="1" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="batchPointForm.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showBatchPoint = false">取消</el-button>
        <el-button type="primary" @click="onBatchPointConfirm">确认</el-button>
      </template>
    </el-dialog>
    <!-- 批量分配客服弹窗 - 已隐藏 -->
    <!-- <el-dialog v-model="showBatchCustomerService" title="批量分配客服" width="600px">
      <el-form :model="batchCustomerServiceForm" label-width="120px">
        <el-form-item label="分配模式">
          <el-radio-group v-model="batchCustomerServiceForm.mode">
            <el-radio label="manual">手动分配</el-radio>
            <el-radio label="auto">自动分配</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="batchCustomerServiceForm.mode === 'manual'" label="选择客服">
          <el-select v-model="batchCustomerServiceForm.selectedServices" multiple placeholder="请选择客服" style="width: 100%">
            <el-option v-for="service in customerServiceList" :key="service" :label="service" :value="service" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="batchCustomerServiceForm.mode === 'manual' && batchCustomerServiceForm.selectedServices.length > 0" label="分配数量">
          <div style="margin-bottom: 8px; color: #666; font-size: 12px;">
            设置每个客服分配多少个待分配会员
          </div>
          <div v-if="batchCustomerServiceForm.selectedServices.length === 1" style="display: flex; align-items: center; gap: 8px;">
            <span style="font-size: 14px; color: #303133;">为 {{ batchCustomerServiceForm.selectedServices[0] }} 分配</span>
            <el-input-number
              v-model="batchCustomerServiceForm.assignCounts[batchCustomerServiceForm.selectedServices[0]]"
              :min="0"
              :max="100"
              size="default"
              style="width: 120px;"
              placeholder="0"
            />
            <span style="font-size: 14px; color: #606266;">个待分配会员</span>
          </div>
          <div v-else style="display: flex; flex-wrap: wrap; gap: 12px;">
            <div v-for="service in batchCustomerServiceForm.selectedServices" :key="service" style="display: flex; align-items: center; gap: 4px;">
              <span style="font-size: 12px; min-width: 60px;">{{ service }}:</span>
              <el-input-number
                v-model="batchCustomerServiceForm.assignCounts[service]"
                :min="0"
                :max="100"
                size="small"
                style="width: 80px;"
                placeholder="0"
              />
            </div>
          </div>
        </el-form-item>

        <el-form-item label="客服工作量">
          <div style="color: #666; font-size: 12px; line-height: 1.5;">
            <div v-for="service in customerServiceList" :key="service" style="margin-bottom: 4px;">
              {{ service }}: {{ getServiceMemberCount(service) }} 个会员
            </div>
            <div style="margin-top: 8px; color: #f56c6c;">
              待分配: {{ getServiceMemberCount('待分配') }} 个会员
            </div>
          </div>
        </el-form-item>

        <el-form-item label="分配说明">
          <div style="color: #666; font-size: 12px; line-height: 1.5;">
            <div v-if="batchCustomerServiceForm.mode === 'manual'">
              <strong>手动分配：</strong>将选中的 {{ multipleSelection.length }} 个会员按轮询方式分配给选中的客服
            </div>
            <div v-else>
              <strong>自动分配：</strong>将选中的 {{ multipleSelection.filter(m => m.customerService === '待分配').length }} 个待分配会员均衡分配给所有客服（优先分配给服务人数最少的客服）
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showBatchCustomerService = false">取消</el-button>
        <el-button type="primary" @click="onBatchCustomerServiceConfirm">确认分配</el-button>
      </template>
    </el-dialog> -->
    <!-- 管理员审核提示 -->
    <el-dialog v-model="showAuditDialog" title="待管理员审核" width="320px" :show-close="false">
      <div>积分变更申请已提交，待管理员审核通过后生效。</div>
      <template #footer>
        <el-button type="primary" @click="showAuditDialog = false">知道了</el-button>
      </template>
    </el-dialog>
    <!-- 显示列弹窗 -->
    <el-dialog v-model="showColumnDialog" title="显示列设置" width="400px">
      <el-checkbox-group v-model="checkedColumns">
        <el-checkbox v-for="col in allColumns" :key="col.prop" :label="col.prop">{{ col.label }}</el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-button @click="showColumnDialog = false">关闭</el-button>
      </template>
    </el-dialog>
    <!-- 编辑备注弹窗 -->
    <el-dialog v-model="showEditRemarkDialog" title="编辑备注" width="500px">
      <el-form :model="editRemarkForm" label-width="80px">
        <el-form-item label="会员信息">
          <div style="color: #666; font-size: 14px;">
            <div>会员ID：{{ editRemarkTarget?.id }}</div>
            <div>会员昵称：{{ editRemarkTarget?.nickname }}</div>
          </div>
        </el-form-item>
        <el-form-item label="备注内容">
          <el-input 
            v-model="editRemarkForm.remark" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入备注内容"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditRemarkDialog = false">取消</el-button>
        <el-button type="primary" @click="saveRemark">保存</el-button>
      </template>
    </el-dialog>

    <!-- C类转B类客户弹窗 -->
    <el-dialog v-model="showConvertToBDialog" title="C类客户转B类客户" width="600px">
      <el-form :model="convertForm" label-width="120px">
        <el-form-item label="会员信息">
          <div>{{ convertTarget?.nickname }} (ID: {{ convertTarget?.id }})</div>
          <div>当前经验值: {{ convertTarget?.points }} 点</div>
        </el-form-item>
        <el-form-item label="转换比例" prop="experienceToAmountRatio">
          <el-input v-model="convertForm.experienceToAmountRatio" suffix="点/万円" />
        </el-form-item>
        <el-form-item label="计算金额" prop="amount">
          <el-input v-model="convertForm.amount" disabled />
          <span slot="suffix" style="margin-left: 5px;">万円</span>
        </el-form-item>
        <el-form-item label="手动修改金额" prop="manualAmount">
          <el-input v-model="convertForm.manualAmount" suffix="万円" />
        </el-form-item>
        <el-form-item label="会员等级">
          <div v-if="convertForm.memberLevel" class="member-level">
            <div class="level-name">{{ convertForm.memberLevel.name }}</div>
            <div class="level-rights">
              <div v-for="(value, key) in convertForm.memberLevel.rights" :key="key">
                {{ getRightName(key) }}: {{ value }}
              </div>
            </div>
          </div>
          <div v-else>无匹配等级</div>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="convertForm.remark" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showConvertToBDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmConvertToB">确认转换</el-button>
      </template>
    </el-dialog>

    <!-- 充值弹窗 -->
    <el-dialog v-model="showRechargeDialog" title="会员充值" width="500px">
      <el-form :model="rechargeForm" label-width="100px">
        <el-form-item label="付款客户ID">
          <el-input v-model="rechargeForm.customerId" disabled />
        </el-form-item>
        <el-form-item label="客户昵称">
          <el-input v-model="rechargeForm.customerName" disabled />
        </el-form-item>
        <el-form-item label="付款日期" required>
          <el-date-picker v-model="rechargeForm.paymentDate" type="datetime" placeholder="选择付款日期时间" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="支付渠道" required>
          <el-select v-model="rechargeForm.paymentChannel" placeholder="请选择支付渠道" style="width: 200px;">
            <el-option label="扫码充值" value="scan" />
            <el-option label="国际汇款" value="wire" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="充值金额" required>
          <el-input-number v-model="rechargeForm.amount" :min="1" :max="10000000" controls-position="right" style="width: 200px;" />
          <span style="margin-left: 8px;">円</span>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="rechargeForm.remark" placeholder="可填写备注" maxlength="50" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showRechargeDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmRecharge">确认充值</el-button>
      </template>
    </el-dialog>

    <!-- 退款弹窗 -->
    <el-dialog v-model="showRefundDialog" title="会员退款" width="500px">
      <el-form :model="refundForm" label-width="100px">
        <el-form-item label="客户ID">
          <el-input v-model="refundForm.customerId" disabled />
        </el-form-item>
        <el-form-item label="客户昵称">
          <el-input v-model="refundForm.customerName" disabled />
        </el-form-item>
        <el-form-item label="退款类型" required>
          <el-radio-group v-model="refundForm.refundType" @change="onRefundTypeChange">
            <el-radio label="withdraw">余额提现</el-radio>
            <el-radio label="transfer">转给好友</el-radio>
            <el-radio label="other">其他</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="refundForm.refundType === 'transfer'" label="选择好友" required>
          <el-select 
            v-model="refundForm.targetFriend" 
            placeholder="搜索并选择好友" 
            filterable 
            style="width: 200px;"
            @change="onFriendChange"
          >
            <el-option 
              v-for="friend in friendList" 
              :key="friend.id" 
              :label="friend.nickname" 
              :value="friend.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="退款日期" required>
          <el-date-picker v-model="refundForm.paymentDate" type="datetime" placeholder="选择退款日期时间" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="退款金额" required>
          <el-input-number v-model="refundForm.amount" :min="1" :max="10000000" controls-position="right" style="width: 200px;" />
          <span style="margin-left: 8px;">円</span>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="refundForm.remark" placeholder="可填写备注" maxlength="50" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showRefundDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmRefund">确认退款</el-button>
      </template>
    </el-dialog>

    <!-- 自动出价配置弹窗 -->
    <AutoBidConfig 
      v-model="showAutoBidDialog"
      :member="autoBidTarget"
      @save="handleAutoBidSave"
    />

    <!-- 创建会员弹窗 -->
    <el-dialog v-model="showCreateMemberDialog" title="创建会员" width="800px">
      <el-form :model="createMemberForm" label-width="120px" :rules="createMemberRules">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="会员昵称" prop="nickname">
              <el-input v-model="createMemberForm.nickname" placeholder="请输入会员昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="createMemberForm.realName" placeholder="请输入真实姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="createMemberForm.phone" placeholder="请输入国际手机号，如：+3348991137" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="createMemberForm.gender" placeholder="请选择性别" style="width: 100%;">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
                <el-option label="未知" value="未知" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生日" prop="birthday">
              <el-date-picker v-model="createMemberForm.birthday" type="date" placeholder="选择生日" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="createMemberForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="会员类型" prop="memberType">
              <el-select v-model="createMemberForm.memberType" placeholder="请选择会员类型" style="width: 100%;" @change="onMemberTypeChange">
                <el-option label="B类" value="B" />
                <el-option label="C类" value="C" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="会员等级" prop="level">
              <el-select v-model="createMemberForm.level" placeholder="请选择会员等级" style="width: 100%;">
                <el-option v-for="level in allLevels" :key="level" :label="level" :value="level" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="结算方式">
              <el-input v-model="createMemberForm.settlementType" disabled style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属客服" prop="customerService">
              <el-select v-model="createMemberForm.customerService" placeholder="请选择客服" style="width: 100%;">
                <el-option label="待分配" value="待分配" />
                <el-option v-for="service in customerServiceList" :key="service" :label="service" :value="service" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        

        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="超级客服">
              <el-switch 
                v-model="createMemberForm.superService" 
                active-text="开启"
                inactive-text="关闭"
              />
              <div style="margin-top: 8px; font-size: 12px; color: #909399;">
              </div>
            </el-form-item>
          </el-col>

        </el-row>
        
        <el-form-item label="备注" prop="remark">
          <el-input v-model="createMemberForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreateMemberDialog = false">取消</el-button>
        <el-button type="primary" @click="handleCreateMember">确认创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { Plus, Delete, Check, InfoFilled } from '@element-plus/icons-vue'
import AutoBidConfig from '@/components/AutoBidConfig.vue'


import { savePaymentRecordAPI, getPaymentRecordsAPI } from '@/services/api'
import { addMockPaymentRecord, getMockPaymentRecords, setMockPaymentRecords, generateMockId } from '@/mock/paymentRecords'
import type { PaymentRecord } from '@/services/database'
import { getRateSettings } from '@/services/database'
import { exchangeRateService } from '@/services/exchangeRateService'
import { baseSettingsService } from '@/services/baseSettingsService'

const allLevels = ['L1', 'L2', 'L3', 'L4', 'L5', 'L6', 'L7']
const allTags = ['新用户', '高价值', '活跃', '老客户']
const regionOptions = [
  {
    value: '中国', label: '中国', children: [
      { value: '北京市', label: '北京市', children: [
        { value: '朝阳区', label: '朝阳区' },
        { value: '海淀区', label: '海淀区' }
      ] },
      { value: '广东省', label: '广东省', children: [
        { value: '广州市', label: '广州市' },
        { value: '深圳市', label: '深圳市' }
      ] }
    ]
  },
  {
    value: '日本', label: '日本', children: [
      { value: '东京都', label: '东京都', children: [
        { value: '新宿区', label: '新宿区' },
        { value: '涩谷区', label: '涩谷区' }
      ] },
      { value: '大阪府', label: '大阪府', children: [
        { value: '中央区', label: '中央区' },
        { value: '北区', label: '北区' }
      ] }
    ]
  },
  {
    value: '美国', label: '美国', children: [
      { value: '加利福尼亚州', label: '加利福尼亚州', children: [
        { value: '洛杉矶', label: '洛杉矶' },
        { value: '旧金山', label: '旧金山' }
      ] },
      { value: '纽约州', label: '纽约州', children: [
        { value: '纽约市', label: '纽约市' },
        { value: '布法罗', label: '布法罗' }
      ] }
    ]
  }
]

const searchForm = ref({
  id: '',
  nickname: '',
  phone: '',
  status: '',
  appDownload: '',
  memberType: '',
  settlementType: '',
  customerService: '', // 添加客服筛选字段
  balanceMin: null as number | null,
  balanceMax: null as number | null,
  registerTime: [],
  tags: [] as string[],
  levels: [] as string[],
  region: [],
  isBlacklisted: null as boolean | null,
  superService: null as boolean | null,
  fullDataAccess: null as boolean | null,
  remark: ''
})

const search = ref('')
const statusFilter = ref('在用')
const currentPage = ref(1)
const pageSize = ref(10)

// 创建会员相关
const showCreateMemberDialog = ref(false)
const createMemberForm = ref({
  nickname: '',
  realName: '',
  phone: '',
  gender: '',
  birthday: '',
  email: '',
  memberType: 'B',
  level: 'L1',
  settlementType: 'JPY',
  customerService: '待分配',
  superService: false,
  fullDataAccess: false,
  remark: ''
})

// 创建会员表单验证规则
const createMemberRules = {
  nickname: [
    { required: true, message: '请输入会员昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { min: 1, max: 20, message: '姓名长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^\+33\d{9}$/, message: '请输入正确的国际手机号格式（+33开头）', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  memberType: [
    { required: true, message: '请选择会员类型', trigger: 'change' }
  ],
  level: [
    { required: true, message: '请选择会员等级', trigger: 'change' }
  ],

}

const levels = allLevels
const tagsList = [
  ['新用户'], 
  ['高价值'], 
  ['活跃'], 
  ['老客户'], 
  ['新用户', '活跃'], 
  ['高价值', '老客户'],
  ['新用户', 'VIP客户'],
  ['活跃', '重要客户'],
  ['高价值', '推荐客户']
]
const genders = ['男', '女', '未知']
const yesNo = ['是', '否']

const regionPool = [
  ['中国', '北京市', '朝阳区'],
  ['中国', '广东省', '广州市'],
  ['中国', '广东省', '深圳市'],
  ['日本', '东京都', '新宿区'],
  ['日本', '东京都', '涩谷区'],
  ['日本', '大阪府', '中央区'],
  ['美国', '加利福尼亚州', '洛杉矶'],
  ['美国', '加利福尼亚州', '旧金山'],
  ['美国', '纽约州', '纽约市'],
  ['美国', '纽约州', '布法罗']
]

// 创建会员数据的函数，支持汇率联动
function createMemberData() {
  return Array.from({ length: 30 }, (_, i) => {
    const status = i === 29 ? '已注销' : '在用'
    const region = regionPool[i % regionPool.length]
    const memberType = i % 2 === 0 ? 'B' : 'C'
    
    return {
      id: (10001 + i).toString(),
      nickname: `用户${i + 1}`,
      realName: `姓名${i + 1}`,
      phone: `+33${String(480000000 + i).slice(1)}`,
      gender: genders[i % 3],
      memberType: memberType,
      settlementType: memberType === 'B' ? 'JPY' : 'CNY',
      exchangeRate: null as string | null, // 汇率字段初始化为null，只通过基础设置实时汇率和单独设置获取
      serviceFee: (memberType === 'B' || memberType === 'C') ? (i % 4 === 0 ? '250' : null) : null, // B/C类客户都有手续费，部分客户有单独设置
      serviceRate: memberType === 'B' ? (i % 5 === 0 ? '4.2%' : null) : null, // 只有B类客户有服务费率，部分客户有单独设置
      depositRatio: memberType === 'B' ? (i % 6 === 0 ? '12%' : null) : null, // 只有B类客户有保证金比例，部分客户有单独设置
      email: `user${i + 1}@example.com`,
      address: `${region.join('-')}`,
      registerTime: '2024-06-04 12:02:00',
      firstOrderTime: '2024-06-04 12:02:00',
      appDownload: yesNo[i % 2],
      wechatBind: yesNo[(i + 1) % 2],
      balance: memberType === 'B' ? 
        (i === 0 ? '¥8,888' : // 用户1固定余额8888
         i === 2 ? '¥0' : // 用户3固定余额0
         `¥${(Math.floor(Math.random() * 200000) + 10000).toLocaleString()}`) : '--',
      level: levels[i % 7],
      points: Math.floor(Math.random() * 3000),
      tags: tagsList[i % tagsList.length],
      status,
      region,
      isBlacklisted: i % 10 === 0, // 模拟部分用户在黑名单中
      customerService: getRandomCustomerService(), // 添加客服字段
      superService: i % 5 === 0, // 模拟部分用户开启超级客服
      fullDataAccess: i % 7 === 0, // 模拟部分用户开启数据全见
      remark: i % 3 === 0 ? `备注信息${i + 1}` : '' // 模拟部分用户有备注信息
    }
  })
}

// 客服列表
const customerServiceList = ['张客服', '李客服', '王客服', '赵客服', '孙客服']

// 随机分配客服函数
function getRandomCustomerService() {
  // 30%的概率分配"待分配"状态
  if (Math.random() < 0.3) {
    return '待分配'
  }
  return customerServiceList[Math.floor(Math.random() * customerServiceList.length)]
}

const members = ref(createMemberData())

// 从数据库加载会员的费率设置
async function loadMemberRateSettings() {
  try {
    console.log('开始加载会员费率设置...')
    for (let i = 0; i < members.value.length; i++) {
      const member = members.value[i]
      const savedSettings = await getRateSettings(member.id)
      if (savedSettings) {
        console.log(`会员 ${member.id} 的费率设置:`, savedSettings)
        // 更新会员对象的费率设置
        if (savedSettings.exchange_rate) {
          member.exchangeRate = savedSettings.exchange_rate
          console.log(`会员 ${member.id} 汇率已更新为: ${savedSettings.exchange_rate}`)
        }
        if (savedSettings.service_fee) {
          member.serviceFee = savedSettings.service_fee
        }
        if (savedSettings.service_rate) {
          member.serviceRate = savedSettings.service_rate
        }
        if (savedSettings.deposit_ratio) {
          member.depositRatio = savedSettings.deposit_ratio
        }
      } else {
        console.log(`会员 ${member.id} 没有保存的费率设置`)
      }
    }
    console.log('会员费率设置加载完成')
    console.log('加载后的会员数据:', members.value.slice(0, 3)) // 显示前3个会员的数据
  } catch (error) {
    console.error('加载会员费率设置失败:', error)
  }
}

const filteredData = computed(() => {
  return members.value.filter(m => {
    // 会员ID
    if (searchForm.value.id && m.id !== searchForm.value.id) return false
    // 会员昵称
    if (searchForm.value.nickname && !m.nickname.includes(searchForm.value.nickname)) return false
    // 手机号
    if (searchForm.value.phone && !m.phone.includes(searchForm.value.phone)) return false
    // 用户状态
    if (searchForm.value.status && m.status !== searchForm.value.status) return false
    // APP下载
    if (searchForm.value.appDownload && m.appDownload !== searchForm.value.appDownload) return false
    // 会员类型
    if (searchForm.value.memberType && m.memberType !== searchForm.value.memberType) return false
    // 结算方式
    if (searchForm.value.settlementType && m.settlementType !== searchForm.value.settlementType) return false
    // 所属客服
    if (searchForm.value.customerService && m.customerService !== searchForm.value.customerService) return false
    // 账户余额范围
    const balanceNum = Number(m.balance.replace(/[^\d]/g, ''))
    if (searchForm.value.balanceMin !== null && balanceNum < searchForm.value.balanceMin) return false
    if (searchForm.value.balanceMax !== null && balanceNum > searchForm.value.balanceMax) return false
    // 注册时间范围
    if (searchForm.value.registerTime && searchForm.value.registerTime.length === 2) {
      const t = new Date(m.registerTime).getTime()
      const [start, end] = searchForm.value.registerTime.map(v => new Date(v).getTime())
      if (t < start || t > end) return false
    }
    // 用户标签
    if (searchForm.value.tags && searchForm.value.tags.length > 0 && !searchForm.value.tags.some((tag: string) => m.tags.includes(tag))) return false
    // 用户等级
    if (searchForm.value.levels && searchForm.value.levels.length > 0 && !searchForm.value.levels.includes(m.level)) return false
    // 地区
    if (searchForm.value.region && searchForm.value.region.length > 0) {
      for (let i = 0; i < searchForm.value.region.length; i++) {
        if (m.region[i] !== searchForm.value.region[i]) return false
      }
    }
    // 黑名单
    if (searchForm.value.isBlacklisted !== null && m.isBlacklisted !== searchForm.value.isBlacklisted) return false
    // 超级客服
    if (searchForm.value.superService !== null && m.superService !== searchForm.value.superService) return false
    // 数据全见
    if (searchForm.value.fullDataAccess !== null && m.fullDataAccess !== searchForm.value.fullDataAccess) return false
    // 备注
    if (searchForm.value.remark && !m.remark?.includes(searchForm.value.remark)) return false
    return true
  })
})

const pagedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredData.value.slice(start, start + pageSize.value)
})

function onSearch() {
  currentPage.value = 1
}
function onReset() {
  searchForm.value = {
    id: '',
    nickname: '',
    phone: '',
    status: '',
    appDownload: '',
    memberType: '',
    settlementType: '',
    customerService: '',
    balanceMin: null,
    balanceMax: null,
    registerTime: [],
    tags: [],
    levels: [],
    region: [],
    isBlacklisted: null,
    superService: null,
    fullDataAccess: null,
    remark: ''
  }
  currentPage.value = 1
}

// 会员类型变化处理函数
function onMemberTypeChange(value: string) {
  if (value === 'B') {
    createMemberForm.value.settlementType = 'JPY'
  } else if (value === 'C') {
    createMemberForm.value.settlementType = 'CNY'
  }
}

// 创建会员处理函数
function handleCreateMember() {
  // 生成新的会员ID
  const newId = (10001 + members.value.length).toString()
  
  // 创建新会员对象
  const newMember = {
    id: newId,
    nickname: createMemberForm.value.nickname,
    realName: createMemberForm.value.realName,
    phone: createMemberForm.value.phone,
    gender: createMemberForm.value.gender,
    memberType: createMemberForm.value.memberType,
    settlementType: createMemberForm.value.settlementType,
    exchangeRate: null,
    serviceFee: null,
    serviceRate: null,
    depositRatio: null,
    email: createMemberForm.value.email,
    address: '',
    registerTime: new Date().toLocaleString('zh-CN'),
    firstOrderTime: '',
    appDownload: '否',
    wechatBind: '否',
    balance: '¥0',
    level: createMemberForm.value.level,
    points: 0,
    tags: [],
    status: '在用',
    region: [],
    isBlacklisted: false,
    customerService: createMemberForm.value.customerService,
    birthday: createMemberForm.value.birthday,
    superService: createMemberForm.value.superService,
    fullDataAccess: createMemberForm.value.fullDataAccess,
    remark: createMemberForm.value.remark
  }
  
  // 添加到会员列表
  members.value.unshift(newMember)
  
  // 显示成功消息
  ElMessage.success('会员创建成功！')
  
  // 关闭对话框
  showCreateMemberDialog.value = false
  
  // 重置表单
  createMemberForm.value = {
    nickname: '',
    realName: '',
    phone: '',
    gender: '',
    birthday: '',
    email: '',
    memberType: 'B',
    level: 'L1',
    settlementType: 'JPY',
    customerService: '待分配',
    superService: false,
    fullDataAccess: false,
    remark: ''
  }
}

// 显示列相关
const showColumnDialog = ref(false)


const allColumns = [
  { prop: 'id', label: 'ID', width: 80 },
  { prop: 'memberType', label: '会员类型', width: 90 },
  { prop: 'nickname', label: '昵称', width: 120 },
  { prop: 'realName', label: '真实姓名', width: 120 },
  { prop: 'phone', label: '手机号', width: 140 },
  { prop: 'gender', label: '性别', width: 70 },
  { prop: 'settlementType', label: '结算方式', width: 90 },
  { prop: 'exchangeRate', label: '汇率', width: 100 },
  { prop: 'serviceFee', label: '手续费', width: 120 },
  { prop: 'serviceRate', label: '服务费率', width: 100 },
  { prop: 'depositRatio', label: '保证金比例', width: 100 },
  { prop: 'customerService', label: '所属客服', width: 100 },
  { prop: 'email', label: '邮箱', width: 180 },
  { prop: 'address', label: '地址', width: 180 },
  { prop: 'registerTime', label: '注册时间', width: 160 },
  { prop: 'firstOrderTime', label: '首次下单时间', width: 160 },
  { prop: 'appDownload', label: 'APP下载', width: 90 },
  { prop: 'wechatBind', label: '绑定微信', width: 90 },
  { prop: 'balance', label: '账户余额', width: 110 },
  { prop: 'level', label: '等级', width: 70 },
  { prop: 'points', label: '可用积分', width: 90 },
  { prop: 'tags', label: '用户标签', width: 160 },
  { prop: 'status', label: '用户状态', width: 90 },
  { prop: 'isBlacklisted', label: '黑名单', width: 90 },
  { prop: 'superService', label: '超级客服', width: 90 },
  
  { prop: 'remark', label: '备注', width: 150 }
]
const checkedColumns = ref(allColumns.map(col => col.prop))
const visibleColumns = computed(() => allColumns.filter(col => checkedColumns.value.includes(col.prop)))

// 多选
const multipleSelection = ref<any[]>([])
function handleSelectionChange(val: any[]) {
  multipleSelection.value = val
}

// 批量标签
const showBatchTag = ref(false)
const batchTagForm = ref({ type: 'add', tags: [] })
function onBatchTagConfirm() {
  if (!batchTagForm.value.tags.length) {
    ElMessage.warning('请选择标签')
    return
  }
  multipleSelection.value.forEach(user => {
    if (batchTagForm.value.type === 'add') {
      user.tags = Array.from(new Set([...user.tags, ...batchTagForm.value.tags]))
    } else {
      user.tags = user.tags.filter(tag => !batchTagForm.value.tags.includes(tag))
    }
  })
  ElMessage.success('批量标签操作成功')
  showBatchTag.value = false
}

// 批量积分
const showBatchPoint = ref(false)
const batchPointForm = ref({ type: 'add', points: 1, remark: '' })
const showAuditDialog = ref(false)

// 批量分配客服 - 已隐藏
// const showBatchCustomerService = ref(false)
// const batchCustomerServiceForm = ref({
//   mode: 'manual', // manual: 手动分配, auto: 自动分配
//   selectedServices: [] as string[], // 选中的客服列表
//   assignCounts: {} as Record<string, number>, // 每个客服分配多少个待分配会员
//   distributionMethod: 'round' // round: 轮询分配, random: 随机分配
// })
function onBatchPointConfirm() {
  if (!batchPointForm.value.points || batchPointForm.value.points <= 0) {
    ElMessage.warning('请输入正确的积分数')
    return
  }
  
  // 获取选中的用户昵称列表
  const selectedUsers = multipleSelection.value.map(user => user.nickname)
  
  // 提交到统一的审批队列（这里模拟提交到用户积分管理页面的审批列表）
  const batchApproval = {
    id: Date.now(),
    operationType: 'batch',
    users: selectedUsers,
    type: batchPointForm.value.type,
    amount: batchPointForm.value.points,
    reason: batchPointForm.value.remark || '批量积分调整',
    operator: '系统管理员',
    applyTime: new Date().toLocaleString(),
    status: 'pending'
  }
  
  // 这里应该调用API提交到后端，现在用localStorage模拟
  const existingApprovals = JSON.parse(localStorage.getItem('batchApprovals') || '[]')
  existingApprovals.unshift(batchApproval)
  localStorage.setItem('batchApprovals', JSON.stringify(existingApprovals))
  
  showBatchPoint.value = false
  ElMessage.success(`已提交${selectedUsers.length}个用户的积分调整申请，待管理员审批`)
}

function viewApprovalStatus() {
  // 跳转到用户积分管理页面的待审批标签页
  router.push({
    name: 'pointsUserManage',
    query: { tab: 'approval' }
  })
}

// 批量分配客服相关函数 - 已隐藏
// function onBatchCustomerServiceConfirm() {
//   if (batchCustomerServiceForm.value.mode === 'manual') {
//     const unassignedMembers = multipleSelection.value.filter(m => m.customerService === '待分配')
//     if (unassignedMembers.length === 0) {
//       ElMessage.warning('选中的会员都已分配客服')
//       return
//     }

//     let assignedCount = 0
//     let memberIndex = 0

//     batchCustomerServiceForm.value.selectedServices.forEach(service => {
//       const assignCount = batchCustomerServiceForm.value.assignCounts[service] || 0
      
//       for (let i = 0; i < assignCount && memberIndex < unassignedMembers.length; i++) {
//         unassignedMembers[memberIndex].customerService = service
//         memberIndex++
//         assignedCount++
//       }
//     })

//     ElMessage.success(`已为${assignedCount}个待分配用户分配客服`)
//   } else {
//     // 自动分配逻辑（均衡分配）
//     const unassignedMembers = multipleSelection.value.filter(m => m.customerService === '待分配')
//     if (unassignedMembers.length === 0) {
//       ElMessage.warning('选中的会员都已分配客服')
//       return
//     }

//     const serviceCounts: Record<string, number> = {}
//     customerServiceList.forEach(service => {
//       serviceCounts[service] = members.value.filter(m => m.customerService === service).length
//       })

//     unassignedMembers.forEach(member => {
//       let minCount = Infinity
//       let selectedService = ''
      
//       customerServiceList.forEach(service => {
//         const currentCount = serviceCounts[service]
//         if (currentCount < minCount) {
//           minCount = currentCount
//           selectedService = service
//           }
//       })
      
//       if (selectedService) {
//         member.customerService = selectedService
//         serviceCounts[selectedService]++
//       }
//     })

//     ElMessage.success(`已为${unassignedMembers.length}个待分配用户自动分配客服`)
//   }

//   showBatchCustomerService.value = false
// }

// function openBatchCustomerServiceDialog() {
//   // 重置表单
//   batchCustomerServiceForm.value = {
//     mode: 'manual',
//     selectedServices: [],
//     assignCounts: {},
//     distributionMethod: 'round'
//   }
//   showBatchCustomerService.value = true
// }

function getServiceMemberCount(service: string): number {
  return members.value.filter(m => m.customerService === service).length
}




function onShowDetail(row: any) {
  router.push({
    name: 'memberDetail',
    params: { id: row.id, nickname: encodeURIComponent(row.nickname) },
    query: { ...route.query }
  })
}

function viewPaymentDetail(row: any) {
  router.push({
    name: 'memberPayment',
    params: { id: row.id, nickname: row.nickname },
    query: { ...route.query }
  })
}

// 处理URL参数中的会员ID
const route = useRoute()
const router = useRouter()

// 处理会员ID查询的函数
const handleMemberIdQuery = () => {
  // 检查URL中是否有id参数
  const memberId = route.query.id
  if (memberId) {
    // 查找对应ID的会员
    const member = members.value.find(m => m.id === Number(memberId) || m.id === memberId)
    if (member) {
      // 找到会员后，在列表中显示该会员
      ElMessage.success(`已找到会员ID: ${memberId}`)
    
      // 将搜索表单中的相关字段设置为该会员的信息
      // 这样可以在列表中筛选出该会员
      searchForm.value.id = member.id
      onSearch() // 触发搜索
    } else {
      ElMessage.warning(`未找到ID为 ${memberId} 的会员`)
    }
  }
}

// 在组件挂载时处理URL参数
onMounted(async () => {
  console.log('会员列表页面开始初始化...')
  handleMemberIdQuery()
  
  // 加载会员费率设置
  console.log('开始调用 loadMemberRateSettings...')
  try {
    await loadMemberRateSettings()
    console.log('loadMemberRateSettings 调用完成')
  } catch (error) {
    console.error('loadMemberRateSettings 调用失败:', error)
  }
  
  // 添加汇率变化监听器
  exchangeRateService.addRateChangeListener((newRate) => {
    console.log('汇率已更新，刷新会员列表显示:', newRate)
    // 汇率更新时不需要重新生成数据，因为汇率字段现在都是null
    // 汇率显示通过getDefaultExchangeRate()函数实时获取
  })
})

// 监听路由参数变化，当URL参数变化时重新处理
watch(
  () => route.query.id,
  (newId) => {
    if (newId) {
      handleMemberIdQuery()
    }
  }
)



function maskAnyPhone(str: string) {
  if (!str) return '';
  // 匹配+开头或纯数字，7位及以上，保留前3后4
  return str.replace(/(\+?\d{0,3})?(\d{3})(\d{4})(\d{0,})/g, (m, p1, p2, p3, p4) => {
    return `${p1 || ''}${p2}****${p4}`;
  });
}

// 获取默认汇率（来自基础设置中的汇率管理）
function getDefaultExchangeRate() {
  // 从汇率服务获取当前汇率
  const rate = exchangeRateService.getCurrentRate()
  console.log('会员列表获取的默认汇率:', rate)
  console.log('localStorage中的汇率:', localStorage.getItem('exchangeRate'))
  return rate
}

// 获取会员的汇率（优先级：会员自定义汇率 > 基础设置实际汇率）
function getMemberExchangeRate(member: any) {
  // 如果会员有自定义汇率设置，优先使用
  if (member.exchangeRate) {
    return member.exchangeRate
  }
  
  // 否则使用基础设置中保存的实际汇率
  const savedActualRate = localStorage.getItem('exchangeRate')
  if (savedActualRate) {
    return parseFloat(savedActualRate).toFixed(4)
  }
  
  // 如果没有保存的实际汇率，则使用汇率服务中的当前汇率
  return exchangeRateService.getCurrentRate()
}

// 获取默认手续费（根据会员类型和基础设置）
function getDefaultServiceFee(memberType: string, exchangeRate?: string, site?: string) {
  if (memberType === 'B') {
    return baseSettingsService.getServiceFeeForB(10000, site || '煤炉').toString() // 使用示例金额10000
  } else if (memberType === 'C') {
    return baseSettingsService.getServiceFeeForC(10000, site || '雅虎日拍').toString() // 使用示例金额10000
  }
  return '200' // 默认手续费
}

// 获取所有站点的默认手续费
function getDefaultServiceFeeSites(memberType: string) {
  if (memberType === 'B' || memberType === 'C') {
    const settings = baseSettingsService.getServiceFeeSettings(memberType)
    return settings.map(s => ({
      site: s.site,
      fee: s.fee
    }))
  }
  return []
}

// 获取基础设置收费管理页面的费率标签（按图片中的显示方式）
function getDefaultServiceFeeTags(memberType: string) {
  if (memberType === 'B' || memberType === 'C') {
    const settings = baseSettingsService.getServiceFeeSettings(memberType)
    
    // 转换为标签格式：站点:手续费円
    return settings.map(setting => ({
      id: setting.id,
      site: setting.site,
      fee: setting.fee
    }))
  }
  return []
}

// 获取所有站点的默认服务费率
function getDefaultServiceRateSites(memberType: string) {
  if (memberType === 'B') {
    const settings = baseSettingsService.getServiceRateSettings()
    return settings.map(s => ({
      site: s.site,
      rate: s.rate
    }))
  }
  return []
}

// 获取所有站点的默认保证金比例
function getDefaultDepositRatioSites(memberType: string) {
  if (memberType === 'B') {
    const settings = baseSettingsService.getDepositRateSettings()
    return settings.map(s => ({
      site: s.site,
      ratio: s.rate
    }))
  }
  return []
}

// 获取默认服务费率（只有B类客户）
function getDefaultServiceRate(memberType: string) {
  if (memberType === 'B') {
    return baseSettingsService.getDefaultServiceRate().toString() + '%'
  }
  return '0%'
}

// 获取默认保证金比例（只有B类客户）
function getDefaultDepositRatio(memberType: string) {
  if (memberType === 'B') {
    return baseSettingsService.getDefaultDepositRate().toString() + '%'
  }
  return '0%'
}

const showRechargeDialog = ref(false)
const rechargeForm = ref({ 
  customerId: '', 
  customerName: '', 
  amount: 0, 
  paymentDate: new Date(), 
  paymentChannel: 'scan', 
  remark: '',
  createTime: '' // 记录用户点击充值按钮的时间
})
const rechargeTarget = ref<any>(null)

// 退款相关
const showRefundDialog = ref(false)
const refundForm = ref({
  customerId: '',
  customerName: '',
  refundType: 'withdraw',
  targetFriend: '',
  paymentDate: new Date(),
  amount: 0,
  remark: '',
  createTime: '' // 记录用户点击退款按钮的时间
})
const refundTarget = ref<any>(null)

// 编辑备注相关
const showEditRemarkDialog = ref(false)
const editRemarkForm = ref({
  remark: ''
})
const editRemarkTarget = ref<any>(null)

// Mock好友列表
const friendList = ref([
  { id: 10002, nickname: '用户2' },
  { id: 10003, nickname: '用户3' },
  { id: 10004, nickname: '用户4' },
  { id: 10005, nickname: '用户5' },
  { id: 10006, nickname: '用户6' },
  { id: 10007, nickname: '用户7' },
  { id: 10008, nickname: '用户8' },
  { id: 10009, nickname: '用户9' },
  { id: 10010, nickname: '用户10' }
])

// 支付渠道名称映射
function getChannelName(channel: string) {
  const channelMap: { [key: string]: string } = {
    'scan': '扫码充值',
    'wire': '国际汇款',
    'other': '其他',
    'alipay': '支付宝',
    'wechat': '微信支付',
    'bank': '银行卡',
    'paypal': 'PayPal',
    'transfer': '转给好友',
    'withdraw': '余额提现',
    '好友转账': '好友转账'
  }
  return channelMap[channel] || channel
}

// 保存支付记录到数据库
async function savePaymentRecordToDB(memberId: string, record: PaymentRecord) {
  try {
    if (isMockMode()) {
      addMockPaymentRecord(memberId, record)
      console.log('支付记录已保存到Mock仓库')
      return
    }
    const success = await savePaymentRecordAPI(record)
    if (success) {
      console.log('支付记录已保存到数据库')
    } else {
      ElMessage.error('保存支付记录失败')
    }
  } catch (error) {
    console.error('保存支付记录失败:', error)
    ElMessage.error('保存支付记录失败')
  }
}

// 是否启用Mock模式
function isMockMode(): boolean {
  const flag = localStorage.getItem('mockPayments')
  return flag === '1' || /[?&]mock=1(&|$)/.test(window.location.search)
}

// 更新Mock记录的工具函数
function updateMockRecord(memberId: string, recordId: string, updater: (r: PaymentRecord) => PaymentRecord) {
  const list = getMockPaymentRecords(memberId)
  const updated = list.map(r => (r.id === recordId ? updater({ ...r }) : r))
  setMockPaymentRecords(memberId, updated)
}

function openRechargeDialog(row: any) {
  rechargeTarget.value = row
  rechargeForm.value.customerId = row.id
  rechargeForm.value.customerName = row.nickname
  rechargeForm.value.amount = 0
  rechargeForm.value.paymentDate = new Date()
  rechargeForm.value.paymentChannel = 'scan'
  rechargeForm.value.remark = ''
  // 记录用户点击充值按钮的时间
  rechargeForm.value.createTime = new Date().toLocaleString()
  showRechargeDialog.value = true
}

async function confirmRecharge() {
  if (!rechargeForm.value.amount || rechargeForm.value.amount <= 0) {
    ElMessage.warning('请输入正确的充值金额')
    return
  }
  if (!rechargeForm.value.paymentDate) {
    ElMessage.warning('请选择付款日期')
    return
  }
  if (!rechargeForm.value.paymentChannel) {
    ElMessage.warning('请选择支付渠道')
    return
  }
  
  // 从数据库获取真实余额
  if (rechargeTarget.value) {
    try {
      // 获取该会员的所有支付记录
      const existingRecords = isMockMode()
        ? getMockPaymentRecords(rechargeTarget.value.id)
        : await getPaymentRecordsAPI(rechargeTarget.value.id)
      
      // 计算真实余额
      let realBalance = 0
      if (existingRecords.length > 0) {
        // 按时间排序，取最后一条记录的余额
        const sortedRecords = existingRecords.sort((a, b) => 
          new Date(a.payment_date).getTime() - new Date(b.payment_date).getTime()
        )
        const lastRecord = sortedRecords[sortedRecords.length - 1]
        realBalance = Number(lastRecord.balance.replace(/[^0-9]/g, ''))
      }
      
      // 计算新余额
      const newBalance = realBalance + rechargeForm.value.amount
      
      // 生成支付记录
      const paymentRecord: PaymentRecord = {
        id: `PAY${Date.now()}`,
        member_id: rechargeTarget.value.id,
        payment_type: 'recharge',
        amount: rechargeForm.value.amount.toString(),
        balance: `¥${newBalance.toLocaleString()}`,
        currency: 'JPY',
        payment_channel: getChannelName(rechargeForm.value.paymentChannel),
        remark: rechargeForm.value.remark || '充值',
        status: 'success',
        payment_date: rechargeForm.value.paymentDate.toLocaleString(),
        transaction_id: `TXN${Date.now()}`,
        create_time: rechargeForm.value.createTime, // 用户点击充值按钮的时间
        operator: '管理员',
        related_record_id: undefined,
        is_revoked: 0
      }
      
      // 保存
      await savePaymentRecordToDB(rechargeTarget.value.id, paymentRecord)
      
      // 立即关闭弹窗
      showRechargeDialog.value = false
      ElMessage.success('充值成功！')
      console.log('充值弹窗已关闭，支付记录已保存')
    } catch (error) {
      console.error('充值失败:', error)
      ElMessage.error('充值失败，请重试')
    }
  }
}

// 退款相关方法
function openRefundDialog(row: any) {
  refundTarget.value = row
  refundForm.value.customerId = row.id
  refundForm.value.customerName = row.nickname
  refundForm.value.refundType = 'withdraw'
  refundForm.value.targetFriend = ''
  refundForm.value.paymentDate = new Date()
  refundForm.value.amount = 0
  refundForm.value.remark = ''
  // 记录用户点击退款按钮的时间
  refundForm.value.createTime = new Date().toLocaleString()
  showRefundDialog.value = true
}



function onRefundTypeChange() {
  // 当退款类型改变时，清空相关字段
  refundForm.value.targetFriend = ''
  refundForm.value.remark = ''
}

function onFriendChange() {
  // 当选择好友时，自动填写备注
  if (refundForm.value.targetFriend) {
    const selectedFriend = friendList.value.find(f => f.id.toString() === refundForm.value.targetFriend.toString())
    if (selectedFriend) {
      refundForm.value.remark = `转给${selectedFriend.nickname}好友`
    }
  }
}

// 为收款用户创建收款记录
async function createReceiveRecord(receiverId: string, amount: number, senderName: string, relatedRecordId?: string) {
  try {
    // 获取收款用户的现有记录以计算新余额
    const existingRecords = isMockMode()
      ? getMockPaymentRecords(receiverId)
      : await getPaymentRecordsAPI(receiverId)
    
    // 计算收款用户的当前余额
    let currentBalance = 0
    if (existingRecords.length > 0) {
      // 过滤有效记录并按时间排序
      const validRecords = existingRecords.filter(r => r.status !== 'revoked')
      const sortedRecords = validRecords.sort((a, b) => {
        const normalizeDate = (dateStr: string) => {
          return dateStr.replace(/(\d{4})\/(\d{1,2})\/(\d{1,2})/, (match: string, year: string, month: string, day: string) => {
            return `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`
          })
        }
        const dateA = new Date(normalizeDate(a.payment_date)).getTime()
        const dateB = new Date(normalizeDate(b.payment_date)).getTime()
        return dateA - dateB
      })
      
      // 重新计算余额
      let balance = 0
      sortedRecords.forEach(record => {
        const recordAmount = Number(record.amount)
        if (record.payment_type === 'recharge') {
          balance += recordAmount
        } else if (record.payment_type === 'deduction') {
          balance -= recordAmount
        }
      })
      currentBalance = balance
    }
    
    // 计算收款后的新余额
    const newBalance = currentBalance + amount
    
    // 生成收款记录
    const receiveRecord: PaymentRecord = {
      id: isMockMode() ? generateMockId('RECEIVE') : `RECEIVE${Date.now()}`,
      member_id: receiverId,
      payment_type: 'recharge', // 收款在系统中显示为充值
      amount: amount.toString(),
      balance: `¥${newBalance.toLocaleString()}`,
      currency: 'JPY',
      payment_channel: '好友转账',
      remark: `来自${senderName}好友`,
      status: 'success',
      payment_date: refundForm.value.paymentDate.toLocaleString(),
      transaction_id: isMockMode() ? generateMockId('TXN') : `TXN${Date.now()}`,
      create_time: new Date().toLocaleString(),
      operator: '系统',
      related_record_id: relatedRecordId, // 关联到转出记录
      is_revoked: 0
    }
    
    // 保存收款记录
    await savePaymentRecordToDB(receiverId, receiveRecord)
    console.log(`已为用户${receiverId}创建收款记录: ${amount}円`)
    
    // 返回生成的记录ID
    return receiveRecord.id
    
  } catch (error) {
    console.error('创建收款记录失败:', error)
    throw error
  }
}

async function confirmRefund() {
  if (!refundForm.value.amount || refundForm.value.amount <= 0) {
    ElMessage.warning('请输入正确的退款金额')
    return
  }
  if (refundForm.value.refundType === 'transfer' && !refundForm.value.targetFriend) {
    ElMessage.warning('请选择转款好友')
    return
  }
  
  // 从数据库获取真实余额
  if (refundTarget.value) {
    try {
      // 获取该会员的所有支付记录
      const existingRecords = isMockMode()
        ? getMockPaymentRecords(refundTarget.value.id)
        : await getPaymentRecordsAPI(refundTarget.value.id)
      
      // 计算真实余额
      let realBalance = 0
      if (existingRecords.length > 0) {
        // 过滤有效记录并按时间排序
        const validRecords = existingRecords.filter(r => r.status !== 'revoked')
        const sortedRecords = validRecords.sort((a, b) => {
          const normalizeDate = (dateStr: string) => {
            return dateStr.replace(/(\d{4})\/(\d{1,2})\/(\d{1,2})/, (match: string, year: string, month: string, day: string) => {
              return `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`
            })
          }
          const dateA = new Date(normalizeDate(a.payment_date)).getTime()
          const dateB = new Date(normalizeDate(b.payment_date)).getTime()
          return dateA - dateB
        })
        
        // 重新计算余额
        let balance = 0
        sortedRecords.forEach(record => {
          const recordAmount = Number(record.amount)
          if (record.payment_type === 'recharge') {
            balance += recordAmount
          } else if (record.payment_type === 'deduction') {
            balance -= recordAmount
          }
        })
        realBalance = balance
      }
      
      console.log('计算出的真实余额:', realBalance, '转账金额:', refundForm.value.amount)
      
      // 检查余额是否足够（允许负数余额，但需要提示用户）
      if (realBalance < refundForm.value.amount) {
        if (realBalance < 0) {
          // 如果余额为负数，询问用户是否继续
          const confirmTransfer = confirm(`警告：用户当前余额为负数 ¥${realBalance.toLocaleString()}，是否继续转账 ¥${refundForm.value.amount.toLocaleString()}？`)
          if (!confirmTransfer) {
            return
          }
        } else {
          ElMessage.warning(`余额不足，无法退款。当前余额: ¥${realBalance.toLocaleString()}，转账金额: ¥${refundForm.value.amount.toLocaleString()}`)
          return
        }
      }
      
      // 计算新余额
      const newBalance = realBalance - refundForm.value.amount
      
      // 生成退款支付记录
      const paymentRecord: PaymentRecord = {
        id: isMockMode() ? generateMockId('REFUND') : `REFUND${Date.now()}`,
        member_id: refundTarget.value.id,
        payment_type: 'deduction', // 退款在系统中显示为扣款
        amount: refundForm.value.amount.toString(),
        balance: `¥${newBalance.toLocaleString()}`,
        currency: 'JPY',
        payment_channel: getChannelName(refundForm.value.refundType === 'transfer' ? 'transfer' : 'withdraw'),
        remark: refundForm.value.remark || (refundForm.value.refundType === 'transfer' ? '转给好友' : '余额提现'),
        status: 'success',
        payment_date: refundForm.value.paymentDate.toLocaleString(),
        transaction_id: isMockMode() ? generateMockId('TXN') : `TXN${Date.now()}`,
        create_time: refundForm.value.createTime, // 用户点击退款按钮的时间
        operator: '管理员',
        related_record_id: undefined, // 这里先设为undefined，转账时会更新
        is_revoked: 0
      }
      
      // 保存到数据库
      await savePaymentRecordToDB(refundTarget.value.id, paymentRecord)
      
      // 如果是转给好友，给收款用户创建收款记录
      if (refundForm.value.refundType === 'transfer' && refundForm.value.targetFriend) {
        const targetFriend = friendList.value.find(f => f.id.toString() === refundForm.value.targetFriend.toString())
        if (targetFriend) {
          // 创建收款记录，并将转出记录ID作为关联ID
          const receiveRecordId = await createReceiveRecord(refundForm.value.targetFriend, refundForm.value.amount, refundTarget.value.nickname, paymentRecord.id)
          
          // 更新转出记录的关联ID，建立双向关联
          paymentRecord.related_record_id = receiveRecordId
          await savePaymentRecordToDB(refundTarget.value.id, paymentRecord)
          
          ElMessage.success(`已成功转款${refundForm.value.amount}円给${targetFriend.nickname}`)
          
          // 提示用户刷新收款用户的支付明细页面
          ElMessage.info(`提示：收款用户${targetFriend.nickname}的支付明细页面需要刷新才能看到转账记录（Mock模式可直接刷新页面或切到该用户详情查看）`)
        }
      } else {
        ElMessage.success('退款成功！')
      }
      
      // 立即关闭弹窗
      showRefundDialog.value = false
      console.log('退款弹窗已关闭，支付记录已保存')
    } catch (error) {
      console.error('退款失败:', error)
      ElMessage.error('退款失败，请重试')
    }
  }
}

// 自动出价配置相关
const showAutoBidDialog = ref(false)
const autoBidTarget = ref<any>(null)

function openAutoBidDialog(member: any) {
  autoBidTarget.value = member
  showAutoBidDialog.value = true
}

function handleAutoBidSave(config: any) {
  ElMessage.success('自动出价配置保存成功')
  // 这里可以添加其他保存后的逻辑
}

// C类转B类客户相关函数 - 新增代码开始
const showConvertToBDialog = ref(false)
const convertForm = ref({
  experienceToAmountRatio: 100, // 经验值转金额比例，默认100点=1万円
  amount: 0, // 计算后的金额
  manualAmount: 0, // 手动修改的金额
  memberLevel: null, // 自动判断的会员等级
  remark: ''
})
const convertTarget = ref<any>(null)

// B类会员等级数据，从MemberLevel.vue中获取
const bLevelList = ref([
  {
    id: 1,
    name: '青铜VIP',
    minAmount: 0,
    maxAmount: 10,
    rights: {
      auctionItems: '无限制',
      auctionLimit: '2倍',
      creditMultiplier: 0,
      photoService: '300円/件',
      packageForwarding: '300円/包裹',
      storagePeriod: '14天',
      pointsRebate: '0.1%'
    }
  },
  {
    id: 2,
    name: '白银VIP',
    minAmount: 10,
    maxAmount: 50,
    rights: {
      auctionItems: '无限制',
      auctionLimit: '3.5倍',
      creditMultiplier: 0,
      photoService: '300円/件',
      packageForwarding: '300円/包裹',
      storagePeriod: '20天',
      pointsRebate: '0.1%'
    }
  },
  {
    id: 3,
    name: '黄金VIP',
    minAmount: 50,
    maxAmount: 100,
    rights: {
      auctionItems: '无限制',
      auctionLimit: '3.5倍',
      creditMultiplier: 0,
      photoService: '300円/件',
      packageForwarding: '300円/包裹',
      storagePeriod: '30天',
      pointsRebate: '0.15%'
    }
  },
  {
    id: 6,
    name: '王者VIP',
    minAmount: 500,
    maxAmount: null,
    rights: {
      auctionItems: '无限制',
      auctionLimit: '5倍',
      creditMultiplier: 1,
      photoService: '免费',
      packageForwarding: '免费',
      storagePeriod: '无限制',
      pointsRebate: '0.2%'
    }
  }
])

// 根据金额判断会员等级
function getMemberLevelByAmount(amount: number) {
  return bLevelList.value.find(level => {
    if (level.maxAmount === null) {
      return amount >= level.minAmount
    }
    return amount >= level.minAmount && amount < level.maxAmount
  }) || null
}

// 添加getRightName函数，用于将权益键名转换为中文名称
function getRightName(key: string) {
  const rightNames: Record<string, string> = {
    'auctionItems': '竞拍商品',
    'auctionLimit': '竞拍额度',
    'creditMultiplier': '信用倍数',
    'photoService': '拍照服务',
    'packageForwarding': '包裹转发',
    'storagePeriod': '仓储期限',
    'pointsRebate': '积分返利'
  }
  return rightNames[key] || key
}

function openConvertToBDialog(member: any) {
  convertTarget.value = member
  // 计算默认的经验值转金额比例和金额
  convertForm.value.experienceToAmountRatio = 100 // 默认100点=1万円
  // 基于会员的经验值计算金额
  const calculatedAmount = Math.floor(member.points / convertForm.value.experienceToAmountRatio)
  convertForm.value.amount = calculatedAmount
  convertForm.value.manualAmount = calculatedAmount
  // 根据金额判断会员等级
  convertForm.value.memberLevel = getMemberLevelByAmount(calculatedAmount)
  convertForm.value.remark = ''
  
  showConvertToBDialog.value = true
}

// 监听手动修改金额事件
watch(() => convertForm.value.manualAmount, (newValue) => {
  if (newValue !== null && newValue !== undefined) {
    convertForm.value.memberLevel = getMemberLevelByAmount(newValue)
  }
})

// 添加监听转换比例变化的事件
watch(() => convertForm.value.experienceToAmountRatio, (newValue) => {
  if (newValue !== null && newValue !== undefined && newValue > 0 && convertTarget.value) {
    const calculatedAmount = Math.floor(convertTarget.value.points / newValue)
    convertForm.value.amount = calculatedAmount
    // 如果手动修改金额与计算金额相同，则同时更新会员等级
    if (convertForm.value.manualAmount === convertForm.value.amount) {
      convertForm.value.memberLevel = getMemberLevelByAmount(calculatedAmount)
    }
  }
})

async function confirmConvertToB() {
  if (!convertTarget.value) return
  
  // 验证输入
  if (!convertForm.value.experienceToAmountRatio || convertForm.value.experienceToAmountRatio <= 0) {
    ElMessage.warning('请输入有效的转换比例')
    return
  }
  if (convertForm.value.manualAmount < 0) {
    ElMessage.warning('金额不能为负数')
    return
  }
  if (!convertForm.value.memberLevel) {
    ElMessage.warning('未找到对应的会员等级，请检查金额是否有效')
    return
  }
  
  try {
    // 这里应该调用API来转换会员类型
    console.log('转换C类会员到B类:', convertTarget.value.id, convertForm.value)
    
    // 模拟API调用成功
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 更新本地数据
    convertTarget.value.memberType = 'B'
    convertTarget.value.memberLevel = convertForm.value.memberLevel.name
    convertTarget.value.rights = convertForm.value.memberLevel.rights
    convertTarget.value.settlementType = 'JPY'
    
    ElMessage.success('会员类型转换成功')
    showConvertToBDialog.value = false
  } catch (error) {
    console.error('会员类型转换失败:', error)
    ElMessage.error('会员类型转换失败，请重试')
  }
}
// C类转B类客户相关函数 - 新增代码结束

// 编辑备注相关函数
function openEditRemarkDialog(member: any) {
  editRemarkTarget.value = member
  editRemarkForm.value.remark = member.remark || ''
  showEditRemarkDialog.value = true
}

function saveRemark() {
  if (!editRemarkTarget.value) return
  
  // 更新会员的备注信息
  editRemarkTarget.value.remark = editRemarkForm.value.remark
  
  // 这里可以调用API保存到后端
  console.log('保存备注:', editRemarkTarget.value.id, editRemarkForm.value.remark)
  
  ElMessage.success('备注保存成功')
  showEditRemarkDialog.value = false
}

// 内联编辑备注相关函数
function startEditRemark(member: any) {
  // 重置其他正在编辑的行
  members.value.forEach(m => {
    if (m !== member) {
      m.isEditingRemark = false
      m.tempRemark = ''
    }
  })
  
  member.isEditingRemark = true
  member.tempRemark = member.remark || ''
  
  // 等待DOM更新后聚焦输入框
  nextTick(() => {
    const input = document.querySelector('.remark-edit input') as HTMLInputElement
    if (input) {
      input.focus()
      input.select()
    }
  })
}

function saveRemarkInline(member: any) {
  member.remark = member.tempRemark
  member.isEditingRemark = false
  member.tempRemark = ''
  
  // 这里可以调用API保存到后端
  console.log('保存备注:', member.id, member.remark)
  
  ElMessage.success('备注保存成功')
}

function cancelEditRemark(member: any) {
  member.isEditingRemark = false
  member.tempRemark = ''
}

function getCustomerAvatar(customerId: string) {
  // 模拟头像URL，实际应该从API获取
  return `https://api.dicebear.com/7.x/avataaars/svg?seed=${customerId}`
}

function getCustomerInitials(nickname: string) {
  if (!nickname) return 'U'
  return nickname.substring(0, 2).toUpperCase()
}

// 权益名称映射函数

</script>

<style scoped>
.member-list-view {
  padding: 24px;
}
.toolbar {
  margin-bottom: 16px;
  display: flex;
  gap: 12px;
}
.table-toolbar {
  margin-bottom: 8px;
}
.search-panel {
  margin: 0 0 12px 0;
  padding: 16px 16px 8px 16px;
  background: #fafbfc;
  border: 1px solid #eef1f5;
  border-radius: 10px;
}
.search-panel :deep(.el-form-item) {
  margin-bottom: 12px;
}
.search-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
.range-inputs {
  display: flex;
  align-items: center;
  gap: 8px;
}
.range-inputs .el-input {
  width: 120px;
}
.range-sep {
  color: #909399;
}
/* 让"注册时间"与其他输入左边界对齐：隐藏日期图标，压缩左侧空白 */
.search-panel :deep(.el-date-editor.el-input__wrapper .el-input__prefix) {
  display: none;
}
.search-panel :deep(.el-date-editor.el-input__wrapper) {
  padding-left: 12px;
}
.search-btns {
  display: flex;
  align-items: flex-end;
  justify-content: flex-end;
}

.auto-bid-container {
  padding: 24px;
}

/* 客户信息卡片 */
.customer-info-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
  margin-bottom: 24px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.customer-avatar {
  margin-right: 16px;
}

.customer-details {
  flex: 1;
}

.customer-name {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 4px;
}

.customer-meta {
  display: flex;
  gap: 16px;
  font-size: 14px;
  opacity: 0.9;
}

.customer-status {
  margin-left: auto;
}

/* 配置区域 */
.config-area {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 开关区域 */
.switch-section {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #e9ecef;
}

.switch-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.switch-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.switch-label {
  font-size: 16px;
  font-weight: 600;
  color: #495057;
}

.switch-desc {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #6c757d;
  font-size: 14px;
}

/* 账号配置区域 */
.accounts-config-section {
  background: white;
  border-radius: 12px;
  border: 1px solid #e9ecef;
  overflow: hidden;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #495057;
  margin: 0;
}

.section-subtitle {
  font-size: 14px;
  color: #6c757d;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.add-account-btn {
  background: linear-gradient(135deg, #409eff 0%, #337ab7 100%);
  border: none;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.account-count {
  font-size: 14px;
  color: #6c757d;
  font-weight: 500;
}

/* 账号列表 */
.accounts-list {
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  max-height: 400px;
  overflow-y: auto;
}

/* 添加账号按钮区域 */
.add-account-section {
  padding: 20px 24px;
  background: #f8f9fa;
  border-top: 1px solid #e9ecef;
  display: flex;
  justify-content: center;
}

.add-account-btn {
  background: linear-gradient(135deg, #409eff 0%, #337ab7 100%);
  border: none;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  padding: 12px 24px;
  font-size: 14px;
  font-weight: 500;
}

.account-card {
  background: white;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.account-card:hover {
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.account-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.account-order {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.order-number {
  width: 32px;
  height: 32px;
  background: linear-gradient(135deg, #409eff 0%, #337ab7 100%);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 14px;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.3);
}

.order-label {
  font-size: 12px;
  color: #6c757d;
  font-weight: 500;
}

.account-actions {
  display: flex;
  gap: 8px;
}

.delete-btn {
  color: #dc3545;
}

.account-content {
  padding: 20px;
  display: grid;
  grid-template-columns: 1fr 200px;
  gap: 20px;
  align-items: end;
}

.account-selector, .times-config {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.selector-label, .times-label {
  font-size: 14px;
  font-weight: 500;
  color: #495057;
}

.account-select {
  .el-input__wrapper {
    border-radius: 6px;
  }
}

.times-input {
  .el-input__wrapper {
    border-radius: 6px;
  }
}

/* 账号详情 */
.account-details {
  padding: 16px 20px;
  background: #f8f9fa;
  border-top: 1px solid #e9ecef;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.detail-label {
  font-size: 12px;
  color: #6c757d;
  min-width: 60px;
}

.detail-value {
  font-size: 12px;
  color: #495057;
  font-weight: 500;
}

/* 对话框底部 */
.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding: 20px 24px;
  background: #f8f9fa;
  border-top: 1px solid #e9ecef;
}

.save-btn {
  background: linear-gradient(135deg, #67c23a 0%, #5daf34 100%);
  border: none;
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);
}

/* 选项内容 */
.option-content {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.option-main {
  font-weight: 500;
  color: #495057;
}

.option-sub {
  font-size: 12px;
  color: #6c757d;
}

/* 备注字段样式 */
.remark-text {
  display: inline-block;
  max-width: 140px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: help;
  color: #606266;
  font-size: 13px;
}

.remark-display {
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  padding: 2px 4px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.remark-display:hover {
  background-color: #f5f7fa;
}

.edit-icon {
  font-size: 12px;
  color: #909399;
  opacity: 0;
  transition: opacity 0.2s;
}

.remark-display:hover .edit-icon {
  opacity: 1;
}

.remark-edit {
  width: 100%;
}

.remark-edit .el-input {
  width: 100%;
}

/* 会员等级样式 */
.member-level {
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 10px;
}
.level-name {
  font-weight: bold;
  margin-bottom: 8px;
  color: #1890ff;
}
.level-rights {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 6px;
}
</style>